package com.wj.core.serialize.impl;

import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;
import com.wj.core.serialize.Serializer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author: wangjun
 * @create: 2018-06-01 
 **/
public class HessianSerialize extends Serializer {

  @Override
  public <T> byte[] serialize(T object) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    HessianOutput hessianOutput = new HessianOutput(outputStream);
    try {
      hessianOutput.writeObject(object);
    } catch (IOException e) {
      throw new IllegalStateException(e.getMessage(), e);
    }
    return outputStream.toByteArray();
  }

  @Override
  public <T> Object deserrialize(byte[] bytes, Class<T> Class) {
    ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
    HessianInput hessianInput = new HessianInput(inputStream);
    try {
      return hessianInput.readObject();
    } catch (IOException e) {
      throw new IllegalStateException(e.getMessage(), e);
    }
  }

  public static void main(String[] args) {
    HessianSerialize hessianSerialize = new HessianSerialize();
    String str = "这是一首简单的小情歌";
    final byte[] serialize = hessianSerialize.serialize(str);
    System.out.println("serialize byte :" + serialize);
    System.out.println(hessianSerialize.deserrialize(serialize, String.class));
  }
}
